/*
 * Name: Joon Ho Cho
 * Date: 10/24/2008
 * Course: 15-437
 */
package scheduler.controller;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.mybeans.dao.DAOException;

import scheduler.controller.Action;
import scheduler.databean.User;
import scheduler.model.BookmarkDao;
import scheduler.model.Model;
import scheduler.model.UserDao;




public class Controller extends HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	Model model;
	
    public void init() throws ServletException {
        model = new Model(getServletConfig());

        Action.add(new AddEntryAction(model));
        Action.add(new BrowseAction(model));
        Action.add(new EditAction(model));
        Action.add(new LoginAction(model));
        Action.add(new LogoutAction(model));
        Action.add(new ManageAction(model));
        Action.add(new ModifyEntryAction(model));
        Action.add(new RegisterAction(model));
        Action.add(new RemoveAction(model));
        Action.add(new ScheduleAction(model));
        Action.add(new SavedSchedulesAction(model));
        Action.add(new SetPasswordAction(model));
        
        try {
        	UserDao userDao = model.getUserDao();
        	BookmarkDao bookmarkDao = model.getBookmarkDao();
			if (userDao.getAll().length < 3 || bookmarkDao.getAll().length < 12) {
				if (userDao.getUserByName("Mike") == null) {
					User temp = new User("Mike");
					temp.setPassword("1234");
					userDao.create(temp);
					bookmarkDao.create(temp.getUserName(), "AMERICAblog", "http://www.americablog.com", "This left-leaning blog takes an activist slant on political reporting...");
					bookmarkDao.create(temp.getUserName(), "MobLogic.tv", "http://www.moblogic.tv", "The man-on-the-street interview is as old as TV, but it gets a nice treatment from MobLogic...");
					bookmarkDao.create(temp.getUserName(), "Orato.com", "http://www.orato.com", "One of the better citizen journalism sites we've seen...");
					bookmarkDao.create(temp.getUserName(), "ScotusBlog", "http://www.scotusblog.com", "Want to know what's going on in the chambers of the highest court in the land?");
				}
				if (userDao.getUserByName("Jane") == null) {
					User temp2 = new User("Jane");
					temp2.setPassword("1234");
					userDao.create(temp2);
					bookmarkDao.create(temp2.getUserName(), "Townhall.com", "http://www.townhall.com", "Townhall aggregates content from leading conservative columnists...");
					bookmarkDao.create(temp2.getUserName(), "Truemors", "http://www.truemors.com", "Don't call it a gossip site. Rather, Truemors is a user-generated rumor/news site...");
					bookmarkDao.create(temp2.getUserName(), "BLDG BLOG", "http://bldgblog.blogspot.com", "That Geoff Manaugh's blog has won awards for its eclectic coverage of architectural conjecture...");
					bookmarkDao.create(temp2.getUserName(), "Boston.com: The Big Picture", "http://www.boston.com/bigpicture", "Three times a week, Boston.com's Alan Taylor posts a series of big, beautiful pictures...");
				}
				if (userDao.getUserByName("Tom") == null) {
					User temp3 = new User("Tom");
					temp3.setPassword("1234");
					userDao.create(temp3);
					bookmarkDao.create(temp3.getUserName(), "Earth Album", "http://www.earthalbum.com", "This isn't the first mash-up of Flickr and Google Maps...");
					bookmarkDao.create(temp3.getUserName(), "PicApp", "http://www.picapp.com", "PicApp can make a world of difference on your blog or Web site...");
					bookmarkDao.create(temp3.getUserName(), "SquareAmerica", "http://www.squareamerica.com", "If you're lucky, somewhere in your parents' or grandparents' house...");
					bookmarkDao.create(temp3.getUserName(), "Tag Galaxy", "http://www.taggalaxy.de", "Visual representations of data are nothing new...");
				}
			}
		} catch (DAOException e) {
			e.printStackTrace();
		}
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String nextPage = performTheAction(request);
        sendToNextPage(nextPage,request,response);
    }
    
    /*
     * Extracts the requested action and (depending on whether the user is logged in)
     * perform it (or make the user login).
     * @param request
     * @return the next page (the view)
     */
    private String performTheAction(HttpServletRequest request) {
        HttpSession session     = request.getSession(true);
        String      servletPath = request.getServletPath();
        User        user        = (User) session.getAttribute("user");
        String      action  = getActionName(servletPath);

		try {
			request.setAttribute("registeredUsers", model.getUserDao().getAll());
		} catch (DAOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	
        // System.out.println("servletPath="+servletPath+" requestURI="+request.getRequestURI()+"  user="+user);

        if (action.equals("register.do") || action.equals("login.do") || action.equals("schedule.do") || action.equals("saved-schedules.do") || action.endsWith("browse.do")) {
        	// Allow these actions without logging in
			return Action.perform(action,request);
        }
        
        if (user == null) {
        	// If the user hasn't logged in, direct him to the login page
			return Action.perform("login.do",request);
        }
        
        if (action.equals("start")) {
        	// If he's logged in but back at the /start page, send him to manage his pics
			return Action.perform("manage.do",request);
        }

      	// Let the logged in user run his chosen action
		return Action.perform(action,request);
    }
    
    /*
     * If nextPage is null, send back 404
     * If nextPage starts with a '/', redirect to this page.
     *    In this case, the page must be the whole servlet path including the webapp name
     * Otherwise dispatch to the page (the view)
     *    This is the common case
     * Note: If nextPage equals "image", we will dispatch to /image.  In the web.xml file, "/image"
     *    is mapped to the ImageServlet will which return the image bytes for display.
     */
    private void sendToNextPage(String nextPage, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
    	// System.out.println("nextPage="+nextPage);
    	
    	if (nextPage == null) {
    		response.sendError(HttpServletResponse.SC_NOT_FOUND,request.getServletPath());
    		return;
    	}
    	
    	if (nextPage.charAt(0) == '/') {
			String host  = request.getServerName();
			String port  = ":"+String.valueOf(request.getServerPort());
			if (port.equals(":80")) port = "";
			response.sendRedirect("http://"+host+port+nextPage);
			return;
    	}
    	
   		RequestDispatcher d = request.getRequestDispatcher("/view/"+nextPage);
   		d.forward(request,response);
    }

	/*
	 * Returns the path component after the last slash removing any "extension"
	 * if present.
	 */
    private String getActionName(String path) {
    	// 
        int slash = path.lastIndexOf('/');
        return path.substring(slash+1);
    }
}
